import { ref } from 'vue';
import request from '../utils/request'

export class WebSocketService {
    constructor(url) {
        this.url = url;
        this.ws = null;
        this.isConnected = ref(false);
    }

    connect() {
        return new Promise((resolve, reject) => {
            try {
                this.ws = new WebSocket(this.url);
                
                this.ws.onopen = () => {
                    this.isConnected.value = true;
                    console.log('WebSocket连接成功');
                    resolve();
                };
                
                this.ws.onerror = (error) => {
                    console.error('WebSocket连接错误:', error);
                    reject(error);
                };
                
                this.ws.onclose = () => {
                    this.isConnected.value = false;
                    console.log('WebSocket连接关闭');
                    // 可以在这里添加重连逻辑
                };
            } catch (error) {
                reject(error);
            }
        });
    }

    sendFeature(feature) {
        if (!this.isConnected.value) {
            console.error('WebSocket未连接');
            return;
        }
        
        const featureData = {
            id: feature.getId(),
            type: feature.getGeometry().getType(),
            coordinates: feature.getGeometry().getCoordinates(),
            properties: feature.getProperties()
        };
        
        this.ws.send(JSON.stringify(featureData));
    }

    onMessage(callback) {
        this.ws.onmessage = (event) => {
            try {
                const data = JSON.parse(event.data);
                callback(data);
            } catch (error) {
                console.error('解析消息失败:', error);
            }
        };
    }

    disconnect() {
        if (this.ws) {
            this.ws.close();
        }
    }

    async someMethod() {
        const data = await request({
            url: this.url,
            method: 'get'
        });
        return data;
    }
} 